<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { nextTick, ref } from 'vue';
import { ApiRole } from '../../api';
import { useRoleStore } from '../../store';
import { storeToRefs } from 'pinia';


const {list}=storeToRefs(useRoleStore()) 
const show = ref<boolean>(false)
const model=ref<API.Role.Add>({role_name:""})
const formRef=ref<FormInstance|null>(null)
const emits=defineEmits<{(name:'save',model:API.Role.Add):void}>()
const cancel=async()=>{
    await ElMessageBox.confirm("取消数据会丢失哦？", "提示", { type: "warning" });
    show.value=false
}

const roules: FormRules={
    role_name:[
        {required:true,message:"请输入角色名",trigger:"blur"},
        {min:2,max:10,message:"长度在2到10个字符",trigger:"blur"},
        //@ts-ignore
        {validator:(rule,value,cb)=>{
            if(list.value.some(item=>item.role_name===value)){
                cb(new Error("角色名已存在"))
            }else{
                cb()
            }
            
        },trigger:"blur"
    }
    ]
}
const save=async()=>{
    formRef.value?.validate()
    await ApiRole.add(model.value)
    emits('save',model.value)
    ElMessage.success("添加成功")
    show.value=false
}
defineExpose({
    begin:()=>{
        model.value.role_name=''
        formRef.value?.resetFields()
        nextTick(()=> show.value=true)
    }
})
</script>


<template>
   <el-dialog title="角色添加"  width="500px" v-model="show" >
       <el-form ref="formRef" :model="model" label-width="80px" :rules="roules">
           <el-form-item label="角色名称" prop="role_name">
            <el-input v-model="model.role_name" placeholder="请输入名称" ></el-input>
           </el-form-item>
       </el-form>
       <div slot="footer">
           <el-button @click="cancel">取 消</el-button>
           <el-button type="primary" @click="save">确 定</el-button>
       </div>
   </el-dialog>
</template>

<style scoped>

</style>